#include "widget.h"
#include "ui_widget.h"
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);
  setWindowTitle("HTTP");

}

Widget::~Widget() {
  delete ui;
}


void Widget::showMessage(const QString &info) {
  ui->messageShoxEdit->appendPlainText(info);

}

void Widget::on_btnSend_clicked() {
  QString url = ui->messageEdit->text();

  QUrl url2(url);
  QNetworkRequest request(url2);

  m_reply = m_manager.get(request);

  QObject::connect(m_reply, &QNetworkReply::finished,this, [&]() {
      // 检查是否有错误
      if (m_reply->error() != QNetworkReply::NoError) {
          showMessage("服务器错误："+m_reply->errorString());
          m_reply->deleteLater();
          return;
      }

      // 读取响应内容
      QByteArray html = m_reply->readAll();
      showMessage(QString(html));
      // 释放响应对象
      m_reply->deleteLater();
  });

  QObject::connect(m_reply, &QNetworkReply::errorOccurred,this, [&](QNetworkReply::NetworkError error) {
      //枚举类型转为字符串、方便观测
      QString  strErr = QMetaEnum::fromType<QNetworkReply::NetworkError>().valueToKey( error );
      showMessage("网络错误:"+strErr);
  });


}

